#coding=utf-8
from __future__ import with_statement

from uliweb import expose
import os
from uliweb.orm import get_model, do_

def __begin__():
    from uliweb import function
    return function('require_login')()
    
def get_list_view(c):
    from uliweb.utils.generic import ListView
    from uliweb import request
    from uliweb.core.html import Tag
    from uliweb.utils.common import get_choice
    from sqlalchemy.sql import select,func,and_, or_
    
    def req_id(value, obj):
        return str(Tag('a', value, href=url_for(req_view, id=obj.id)))
    
    def stage(value, obj):
        from uliweb import settings
        if obj.mode:
            return get_choice(settings.get_var('PARA/REQ_STAGE').get(obj.mode, []), value)
        else:
            return ''

    req_manager_report = get_model('manage_requirement_week')
    #取最近的报表日期
    last_date = None
    sql_date = select([func.max(req_manager_report.c.report_date)])
    sql_date_rs = do_(sql_date)
    for row in sql_date_rs:
        last_date = row[0]

    def delay_if(value, obj):
        req = req_manager_report.get((req_manager_report.c.req_id==obj.id)&(req_manager_report.c.report_date == last_date))
        if req:
            delay = req.delay_flag
            if delay:
                return u'是'
        return u'否'

    def plan_stat(value, obj):
        req = req_manager_report.get((req_manager_report.c.req_id==obj.id)&(req_manager_report.c.report_date == last_date))
        if req:
            rate = req.plan_stat
            return str((round(rate,4))*100)+'%'
        else:
            return ''
    def inner_resource_num(value, obj):
        req = req_manager_report.get((req_manager_report.c.req_id==obj.id)&(req_manager_report.c.report_date == last_date))
        if req:
            rate = req.inner_resource_num
            return round(rate,2)
        else:
            return ''
    def inner_input(value, obj):
        req = req_manager_report.get((req_manager_report.c.req_id==obj.id)&(req_manager_report.c.report_date == last_date))
        if req:
            rate = req.inner_resource_input
            return str((round(rate,4))*100)+'%'
        else:
            return ''
    def outer_resource_num(value, obj):
        req = req_manager_report.get((req_manager_report.c.req_id==obj.id)&(req_manager_report.c.report_date == last_date))
        if req:
            rate = req.outer_resource_num
            return round(rate,2)
        else:
            return ''
    def outer_input(value, obj):
        req = req_manager_report.get((req_manager_report.c.req_id==obj.id)&(req_manager_report.c.report_date == last_date))
        if req:
            rate = req.outer_resource_input
            return str((round(rate,4))*100)+'%'
        else:
            return ''
    
    #产生虚拟字段，是否牵头，只有当是开发中心级别人员进入才会处理
    def header(value, obj):
        if obj.main_sys._kfzx_ == request.user._kfzx_ and request.user.is_gm:
            return '<div class="ui-icon ui-icon-check"></div>'
        if not request.user.is_gm and request.user.users_systems.has(obj.main_sys):
            return '<div class="ui-icon ui-icon-check"></div>'
        else:
            return '<div class="ui-icon ui-icon-closethick"></div>'
    
    pageno = int(request.values.get('page', 1)) - 1
    rows_per_page = int(request.values.get('rows', settings.get_var('PARA/ROWS_PER_PAGE', 10)))
    
    User = get_model('user')
    Requirement = get_model('requirement')
    System = get_model('system')
    Tasks_develop = get_model('tasks_develop')
    query = None
    condition = None
    #如果是条线用户，只能看到所属条线的准开发需求
#    query = Requirement.get_user_requirements(request.user, not_in=())
    
    #増加only_mine的处理
    if c.get('only_mine') == '1':
        if request.user.department == '1':
            condition = (Requirement.c.tx == request.user._tx_) & condition
        elif request.user.department == '2':
            if request.user.is_gm:
                condition = Requirement.kfzxs.in_(request.user._kfzx_) & condition
            else:
                ids = request.user.users_systems.ids()
                condition = Requirement.systems.in_(*ids) & condition
    
    #增加显示未完成信息处理
#    if request.GET.get('notcomplete') == '1':
#        condition = (~Requirement.c.stage.in_(['FN', 'CL'])) & condition
    if c.get('tx'):
        condition = (Requirement.c.tx == int(c['tx'])) & condition
    if c.get('kfzx'):
        condition = (Requirement.kfzxs.in_(int(c['kfzx']))) & condition
    if c.get('main_sys_kfzx'):
        condition = (Requirement.c.main_sys.in_(select([System.c.id],and_(System.c.kfzx == int(c['main_sys_kfzx']))))) & condition    
    if c.get('system'):
        condition = (Requirement.systems.in_(int(c['system']))) & condition
    if c.get('mode') and c['mode']:
        condition = (Requirement.c.mode.in_(c['mode'])) & condition
    if c.get('stage') and c['stage']:
        condition = (Requirement.c.stage.in_(c['stage'])) & condition
    if c.get('title'):
        condition = (Requirement.c.title.like('%'+c['title']+'%') | Requirement.c.req_id.like('%'+c['title']+'%')) & condition
    if c.get('care_level'):
        condition = (Requirement.c.care_level == c['care_level']) & condition
    if c.get('begin_date'):
            condition = (Requirement.c.created_date >= c['begin_date']) & condition
    if c.get('end_date'):
            condition = (Requirement.c.created_date <= c['end_date']) & condition
        
    if c.get('closed') != '1':
        condition = (~Requirement.c.stage.in_(['FN', 'CL', '19'])) & condition
    
    if c.get('selfdev_if'):
        condition = (Requirement.c.selfdev_if == c['selfdev_if']) & condition
    if c.get('taskdev_if') and c['taskdev_if'] == '1':
        condition = (Requirement.c.id.in_(select([Tasks_develop.c.requirement]))) & condition
    elif c.get('taskdev_if') and c['taskdev_if'] == '0':
        condition = (~Requirement.c.id.in_(select([Tasks_develop.c.requirement]))) & condition
    sortid = request.GET.get('sortid')
    if sortid:
        if ':' in sorted:
            sortid, desc = sorted.split(':')
        else:
            desc = 'asc'
        if sortid in Requirement.c:
            order_by = Requirement.c[sortid]
            if desc == 'desc':
                order_by = order_by.desc()
    else:
        order_by = [Requirement.c.care_level.desc()]
    
    if request.user.department != '2':
        fields = ('tx', 'req_id', 'care_level', 'created_date', 'title',
            'mode', 'stage', 
            {'name':'plan_stat','verbose_name':'计划进度完成', 'width':80},
            'main_sys', 
            {'name':'delay_if','verbose_name':'是否延迟', 'width':70},
            {'name':'inner_resource_num','verbose_name':'中心实际投入资源(人月)', 'width':135},   
            {'name':'inner_input','verbose_name':'中心实际投入资源较计划', 'width':150},
            {'name':'outer_resource_num','verbose_name':'公司实际投入资源(人月)', 'width':135},  
            {'name':'outer_input','verbose_name':'公司实际投入资源较计划', 'width':150},
            'tx_manager', 'submitter', 'contactor',  'exe_manager',  
            {'name':'systems', 'width':300},           
            )
    else:
        fields = ({'name':'header', 'verbose_name':'牵头方', 'width':40, 'align':'center', 'help_string':'牵头方表示主项目组\n这是一个测试'}, 'tx', 'req_id', 'care_level', 'created_date', 'title',
            'mode', 'stage', 
            {'name':'plan_stat','verbose_name':'计划进度完成', 'width':80},
            'main_sys', 
            {'name':'delay_if','verbose_name':'是否延迟', 'width':70},
            {'name':'inner_resource_num','verbose_name':'中心实际投入资源(人月)', 'width':135},   
            {'name':'inner_input','verbose_name':'中心实际投入资源较计划', 'width':150},
            {'name':'outer_resource_num','verbose_name':'公司实际投入资源(人月)', 'width':135},  
            {'name':'outer_input','verbose_name':'公司实际投入资源较计划', 'width':150},
            'tx_manager', 'submitter', 'contactor', 'exe_manager', 
            {'name':'systems', 'width':300},
            )
    
    fields_convert_map = {'req_id':req_id, 'stage':stage, 'header':header,
            'delay_if':delay_if, 'plan_stat':plan_stat,'inner_resource_num':inner_resource_num,
            'inner_input':inner_input,'outer_resource_num':outer_resource_num,'outer_input':outer_input}
    view =  ListView(Requirement, condition=condition, query=query, fields=fields, order_by=order_by,
        rows_per_page=rows_per_page, pageno=pageno, 
        fields_convert_map=fields_convert_map, id='req_table')
    
    return view
@expose('/events')
def events():
    return {}

@expose('/requirements')
def req():
    from query import create_req_query
    from uliweb.orm import get_model
    from sqlalchemy.sql import select,func
    
    query = create_req_query(url_for(req))
    condition = query.run()
    view = get_list_view(condition)
    if 'download' in request.GET:
        def header(value, obj):
            if obj.main_sys._kfzx_ == request.user._kfzx_ and request.user.is_gm:
                return u'是'
            if not request.user.is_gm and request.user.users_systems.has(obj.main_sys):
                return u'是'
            else:
                return u'否'
            
        def stage(value, obj):
            from uliweb import settings
            from uliweb.utils.common import get_choice
            if obj.mode:
                return unicode(get_choice(settings.get_var('PARA/REQ_STAGE').get(obj.mode, []), value), 'utf8')
            else:
                return ''
        req_manager_report = get_model('manage_requirement_week')
        #取最近的报表日期
        last_date = None
        sql_date = select([func.max(req_manager_report.c.report_date)])
        sql_date_rs = do_(sql_date)
        for row in sql_date_rs:
            last_date = row[0]
        
        def delay_if(value, obj):
            req = req_manager_report.get((req_manager_report.c.req_id==obj.id)&(req_manager_report.c.report_date == last_date))
            if req:
                delay = req.delay_flag
                if delay:
                    return u'是'
            return u'否'
        
        def plan_stat(value, obj):
            req = req_manager_report.get((req_manager_report.c.req_id==obj.id)&(req_manager_report.c.report_date == last_date))
            if req:
                rate = req.plan_stat
                return str((round(rate,4))*100)+'%'
            else:
                return ''
        def inner_resource_num(value, obj):
            req = req_manager_report.get((req_manager_report.c.req_id==obj.id)&(req_manager_report.c.report_date == last_date))
            if req:
                rate = req.inner_resource_num
                return round(rate,2)
            else:
                return ''
        def inner_input(value, obj):
            req = req_manager_report.get((req_manager_report.c.req_id==obj.id)&(req_manager_report.c.report_date == last_date))
            if req:
                rate = req.inner_resource_input
                return str((round(rate,4))*100)+'%'
            else:
                return ''
        def outer_resource_num(value, obj):
            req = req_manager_report.get((req_manager_report.c.req_id==obj.id)&(req_manager_report.c.report_date == last_date))
            if req:
                rate = req.outer_resource_num
                return round(rate,2)
            else:
                return ''
        def outer_input(value, obj):
            req = req_manager_report.get((req_manager_report.c.req_id==obj.id)&(req_manager_report.c.report_date == last_date))
            if req:
                rate = req.outer_resource_input
                return str((round(rate,4))*100)+'%'
            else:
                return ''
        
        fields_convert_map = {'header':header, 'stage':stage, 'delay_if':delay_if, 'plan_stat':plan_stat,'inner_resource_num':inner_resource_num,
            'inner_input':inner_input,'outer_resource_num':outer_resource_num,'outer_input':outer_input}
        return view.download('requirements.xls', action='download', timeout=0,
            fields_convert_map=fields_convert_map)
    elif 'data' in request.values:
#        result = view.run(head=False, body=True)
        return json(view.json())
    else:
        result = view.run(head=True, body=False)
        result.update({'query_form':query.form, 'table':view})
        return result

def requirement_post_save(obj, data):
    from uliweb.orm import get_model
    
    if data['main_sys'] not in data['systems']:
        data['systems'].append(data['main_sys'])
    flag = obj.systems.update(*data['systems'])
    kfzxs = []
    System = get_model('system')
    for s in data['systems']:
        system = System.get(s)
        if system.kfzx not in kfzxs:
            kfzxs.append(system.kfzx)
    f2 = obj.kfzxs.update(*kfzxs)
    return flag or f2

@expose('/requirements/add')
def req_add():
    from uliweb.utils.generic import AddView
    from uliweb.orm import get_model
    from forms import ReqForm
    import generic.views as g_views
    from datetime import date
    
    get_url = g_views.get_url('/requirements', restful=True)
    System = get_model('system')
    
    def pre_save(data):
        #当条线用户时，不需要输入'tx'字段，从用户信息中获取
        if 'tx' not in data:
            data['tx'] = request.user._tx_
            
        Requirement = get_model('requirement')
        year = date.today().year
        v = Requirement.filter(Requirement.c.req_id.like('%02d_%s_%%' % (data['tx'], year))).order_by(Requirement.c.req_id.desc()).values_one('req_id')
        if not v:
            data['req_id'] = '%02d_%s_%04d' % (data['tx'], year, 1)
        else:
            v = v[0]
            data['req_id'] = v[:8] + '%04d' % (int(v[8:])+1)
#        data['modified_user'] = request.user.id
        data['creator'] = request.user.id
        
        if 'attachment' in data and data['attachment']:
            filename,ext = os.path.splitext(data['attachment'].filename)
            data['attachment'].filename = os.path.join(data['req_id'], filename + '_' + date.today().strftime("%Y%m%d") + ext)
        if 'risk_doc' in data and data['risk_doc']:
            filename,ext = os.path.splitext(data['risk_doc'].filename)
            data['risk_doc'].filename = os.path.join(data['req_id'], filename + '_' + date.today().strftime("%Y%m%d") + ext)

    def post_created_form(fcls, model):
        fcls.systems.query = System.filter(System.c.sys_type != '5')
        fcls.main_sys.query = System.filter(System.c.sys_type != '5')
        fcls.mode.choices = settings.get_var("PARA/REQ_MODE_INPUT", [])

    if (request.user.is_superuser) or (request.user.department == '1'):
        from functools import partial
        
        fields = ['title', 'description', 'attachment', 'mode',  
            'main_sys', 'systems', 'risk_doc','memo', 'tx_manager', 'submitter',
            'contactor', 'exe_manager']
        if request.user.is_superuser:
            fields.insert(0, 'tx')
        
        view = AddView('requirement', partial(get_url, action='view'), form_cls=ReqForm, pre_save=pre_save, 
            post_save=requirement_post_save, post_created_form=post_created_form,
            fields=fields)
        return view.run()
    else:
        return error("你无权编辑准开发需求！")

@expose('/requirements/<id>')
def req_view(id):
    from uliweb.utils.generic import DetailView
    from uliweb.orm import get_model
    from uliweb.utils.common import get_choice
    
    def stage(value, obj):
        return get_choice(settings.PARA.REQ_STAGE.get(obj.mode, []), value)
    def selfdev_if(value, obj):
        if obj.selfdev_if:
            selfdev_if = u'是'
        else:
            selfdev_if = u'否'
        return "<span id='selfdev_if'>%s</span>" % selfdev_if
    
    Requirement = get_model('requirement')
    obj = Requirement.get(int(id))
    if not obj:
        error(u'找不到准开发需求 [%s],可能已经被删除' % id)
        
    view = DetailView('requirement', obj=obj)
    view.fields_convert_map = {'stage':stage,'selfdev_if':selfdev_if}
    return view.run()

@expose('/requirements/<id>/edit')
def req_edit(id):
    from uliweb.utils.generic import EditView
    from uliweb.form import TextField
    from plugs.ui.jquery.jquery.widgets import DatePicker
    from uliweb.orm import get_model
    from forms import ReqForm
    from datetime import date
    
    Requirement = get_model('requirement')
    System = get_model('system')
    obj = Requirement.get(Requirement.c.id == int(id))
    
    def post_created_form(fcls, model, obj):
        if request.user.is_superuser:
            fcls.stage.choices = settings.PARA.REQ_STAGE.get(obj.mode, [])
        fcls.systems.query = System.filter(System.c.sys_type != '5') 
    
    def requirement_post_save(obj, data):
        from uliweb.orm import get_model
        
        if obj._main_sys_ not in data['systems']:
            data['systems'].append(obj._main_sys_)
        flag = obj.systems.update(*data['systems'])
        kfzxs = []
        System = get_model('system')
        for s in data['systems']:
            system = System.get(s)
            if system.kfzx not in kfzxs:
                kfzxs.append(system.kfzx)
        f2 = obj.kfzxs.update(*kfzxs)
        return flag or f2
        
    def pre_save(obj, data):
        if 'attachment' in data and data['attachment']:
            filename,ext = os.path.splitext(data['attachment'].filename)
            data['attachment'].filename = os.path.join(data['req_id'], filename + '_' + date.today().strftime("%Y%m%d") + ext)
        else:
            data.pop('attachment', None)
        if 'risk_doc' in data and data['risk_doc']:
            filename,ext = os.path.splitext(data['risk_doc'].filename)
            data['risk_doc'].filename = os.path.join(data['req_id'], filename + '_' + date.today().strftime("%Y%m%d") + ext)
        else:
            data.pop('risk_doc', None)

    if obj.can_modified(request.user):
        if request.user.is_superuser:
            fields = ('tx', 'req_id', 'title', 'description', 'attachment', 'mode',
                'stage', 'refer_req', 'tx_manager', 'submitter', 'contactor', 'exe_manager', 
                'main_sys', 'systems', 'care_level', 'risk_doc', 'memo')
        elif request.user.department == '1' and request.user._tx_ == obj._tx_:
            fields = ('req_id', 'title', 'description', 'attachment', 'mode', 
                'refer_req', 'tx_manager', 'submitter', 'contactor', 'exe_manager',
                'main_sys', 'systems', 'risk_doc', 'memo')
        else:
            fields = ('tx_manager', 'submitter', 'contactor', 'exe_manager', 'systems', 'memo')

        view = EditView('requirement', ok_url=url_for(req_view, id=id), 
            obj=obj, form_cls=ReqForm, post_save=requirement_post_save, 
            post_created_form=post_created_form, fields=fields, pre_save=pre_save)
        return view.run()
    else:
        return error("你无权编辑准开发需求！")

@expose('/requirements/<id>/transfer')
def req_transfer(id):
    from uliweb.utils.generic import EditView
    from uliweb.orm import get_model
    from uliweb.utils.generic import ReferenceSelectField
    
    Requirement = get_model('requirement')
    obj = Requirement.get(int(id))
    static_fields = ('title', 'req_id')
    query = Requirement.get_user_requirements(request.user, not_in=settings.get_var('PARA/REQ_NOT'))
    condition = (Requirement.c.id != obj.id)
    requirement_field = ReferenceSelectField('requirement', query=query, condition=condition, label='待迁入准开发需求')
    fields = ['title', 'req_id', ('requirement', requirement_field)]
    old_requirement = obj.id
    
    def pre_save(obj, data):
        data['stage'] = 'CL'
        
    def post_save(obj, data):
        if old_requirement != data['requirement']:
            new_id = data['requirement']
            new_req = Requirement.get(new_id)
            
            #处理所有任务书,将任务书中原来的准开发需求编号改为新的准开发需求编号
            Assignment = get_model('assignment')
            ass_table = Assignment.requirements.table
            ass_table = do_(ass_table.update(ass_table.c.requirement_id==old_requirement).values(requirement_id=new_id))
                
            #处理准开发需求明细
            RequirementDetails = get_model('requirementdetails')
            do_(RequirementDetails.table.update(RequirementDetails.c.requirement==old_requirement).values(requirement=new_id))

            #处理开发任务
            TaskDevelop = get_model('tasks_develop')
            do_(TaskDevelop.table.update(TaskDevelop.c.requirement==old_requirement).values(requirement=new_id, tx=new_req._tx_))
            
            #处理可研任务
            Researches = get_model('researches')
            do_(Researches.table.update(Researches.c.requirement==old_requirement).values(requirement=new_id, tx=new_req._tx_))
            
            #处理非开发任务
            Tasks = get_model('tasks')
            do_(Tasks.table.update(Tasks.c.requirement==old_requirement).values(requirement=new_id, tx=new_req._tx_))
            
            #处理任务明细
            Tasks_Details = get_model('tasks_details')
            do_(Tasks_Details.table.update(Tasks_Details.c.requirement==old_requirement).values(requirement=new_id, tx=new_req._tx_))
            
            #将原准开发需求的系统合并到新准开发需求中
            ids = obj.systems.all().ids()
            new_req.systems.add(*ids)
            
            #将原准开发需求的开发中心合并到新准开发需求中
            ids = obj.kfzxs.all().ids()
            new_req.kfzxs.add(*ids)
            
            return True
            
    view = EditView('requirement', ok_url=url_for(req_view, id=id), obj=obj, 
        fields=fields, static_fields=static_fields, pre_save=pre_save, post_save=post_save)
    return view.run()

@expose('/requirements/<id>/delete')
def req_delete(id):
    from uliweb.utils.generic import DeleteView
    from uliweb import orm
    
    Requirement = orm.get_model('requirement')
    Tasks = orm.get_model('tasks')
    Tasks_Develop = orm.get_model('tasks_develop')
    Researches = orm.get_model('researches')
    obj = Requirement.get(Requirement.c.id == int(id))
    
    if request.user.is_superuser or (request.user.department == '1' and request.user.is_gm and obj._tx_ == request.user._tx_):
        RequirementDetails = orm.get_model('requirementdetails')
        if RequirementDetails.filter(RequirementDetails.c.requirement==obj.id).count() > 0:
            flash('当前准开发需求下还存在明细信息，请先删除')
            return redirect('/requirements/%d' % obj.id)
        if obj.req_assignments.count() > 0:
            flash('当前准开发需求下还存在与之关联的任务书，请先删除')
            return redirect('/requirements/%d' % obj.id)
        if obj.req_tasks.count() > 0:
            flash('当前准开发需求下还存在与之关联的非开发任务，请先删除')
            return redirect('/requirements/%d' % obj.id)
        if obj.req_researches.count() > 0:
            flash('当前准开发需求下还存在与之关联的可研任务，请先删除')
            return redirect('/requirements/%d' % obj.id)
        if obj.req_tasks_develop.count() > 0:
            flash('当前准开发需求下还存在与之关联的开发任务，请先删除')
            return redirect('/requirements/%d' % obj.id)
        
        view = DeleteView('requirement', ok_url=url_for(req), obj=obj)
        return view.run()
    else:
        return error("你无权删除准开发需求！")

@expose('/requirements/<id>/newstage')
def req_newstage(id):
    from uliweb.utils.generic import AddView
    from uliweb.orm import get_model
    from uliweb.form import SelectField, DateField
    from plugs.ui.jquery.jquery.widgets import DatePicker
    from datetime import datetime, timedelta
    from uliweb.form.template_layout import TemplateLayout
    import generic.views as g_views
    
    get_url = g_views.get_url('/requirements/%s' % id)
    
    Requirement = get_model('requirement')
    obj = Requirement.get(Requirement.c.id == int(id))
    
    data = {}
    data['requirement'] = obj.id
    data['tx'] = obj._tx_
    data['mode'] = obj.mode
    if obj.begin_date == None:
        data['begin_date'] = obj.created_date
    else:
        data['begin_date'] = obj.begin_date
    data['end_date'] = datetime.now()
    data['newstage_begin_date'] = datetime.now() + timedelta(days=1)
    
    #计算下一个阶段
    choices = settings.PARA.REQ_STAGE[obj.mode]
    index = -1
    for i, (x, y) in enumerate(choices):
        if x == obj.stage:
            index = i
            data['stage'] = y
            break
    if obj.stage == '19':
        choices = choices[1:index]
    elif obj.stage == '1A':
        choices = choices[1:index-1]
    else:
        if index > -1:
            choices = choices[index+1:]
    newstage = SelectField('下一阶段', default=choices[0][0], choices=choices, required=True)
    newstage_begin_date = DateField('下一阶段开始日期', required=True, build=DatePicker)
    
    static_fields = ('requirement', 'tx', 'mode', 'stage')
    
    fields = ('requirement', 'tx', 'mode', 'stage', 'begin_date', 'end_date', 
    ('newstage',newstage), ('newstage_begin_date',newstage_begin_date))
    
    def post_created_form(fcls, model):
        fcls.layout_class = TemplateLayout
        fcls.layout = 'layout_req_newstage.html'
        
    def pre_save(data):
        data.update(obj.to_dict(fields=static_fields, convert=False))
        data['requirement'] = obj
        data['tx'] = obj.tx
        data['stage'] = obj.stage
        
    def post_save(o, data):
        #是否完成
        if data['newstage'] == 'FN':
            RequirementDetails = get_model('requirementdetails')
            d = {}
            d['requirement'] = data['requirement']
            d['tx'] = data['tx']
            d['mode'] = data['mode']
            d['stage'] = 'FN'
            d['begin_date'] = data['begin_date']
            d['end_date'] = data['end_date']
            x = RequirementDetails(**d)
            x.save()
                
        #更新准开发需求
        obj.begin_date = data['newstage_begin_date']
        obj.stage = data['newstage']
        obj.save()
        
    from forms import ReqNewstageForm 
    view = AddView('requirementdetails', ok_url='/requirements/%s' % id, fields=fields, form_cls=ReqNewstageForm,
        static_fields=static_fields, data=data, pre_save=pre_save, post_save=post_save, 
        post_created_form=post_created_form)
    
    return g_views.generic_add(get_url=get_url, layout='req_layout.html', 
        title='进入下一阶段', view=view, template='req_newstage.html', data=data)

@expose('/requirements/<id>/details')
def req_details(id):
    from uliweb.orm import get_model
    
    Requirement = get_model('requirement')
    obj = Requirement.get(int(id))
    RequirementDetails = get_model('requirementdetails')
    
    objs = RequirementDetails.filter(RequirementDetails.c.requirement == int(id)).order_by(RequirementDetails.c.end_date.desc())
    
    choices = settings.PARA.REQ_STAGE.get(obj.mode, [])
    
    z = []
    for i in objs:
        for (x,y) in choices:
            if x == i.stage:                
                 z.append(y)
            
    return {'objects':objs, 'object':obj, 'stage':z, 'index':0}
 
@expose('/requirements/details/<id>/edit')
def req_details_edit(id):
    from uliweb.utils.generic import EditView
    from uliweb.orm import get_model
    from uliweb.form import DateField
    from plugs.ui.jquery.jquery.widgets import DatePicker
    from datetime import datetime, date
    from uliweb.form.template_layout import TemplateLayout
    
    RequirementDetails = get_model('requirementdetails')
    obj = RequirementDetails.get(int(id))
    
    old_data = obj.to_dict()
    
    data = {}
    data['requirement'] = obj.requirement.req_id
    data['tx'] = obj.tx.name
    data['mode'] = obj.get_display_value('mode')
    data['begin_date'] = obj.begin_date
    data['end_date'] = obj.end_date
        
    #计算下一个阶段
    choices = settings.PARA.REQ_STAGE.get(obj.mode, [])
    for i, (x, y) in enumerate(choices):
        if x == obj.stage:
            data['stage'] = y
            break
        
    static_fields = ('requirement', 'tx', 'mode', 'stage')
        
    fields = ('requirement', 'tx', 'mode', 'stage', 'begin_date', 'end_date')
        
    def post_created_form(fcls, model, obj):
        fcls.layout_class = TemplateLayout
        fcls.layout = 'layout_req_details_edit.html'
            
    def pre_save(obj, data):
        for k in static_fields:
            del data[k]
        data['requirement'] = obj.requirement
        data['tx'] = obj.tx
        data['stage'] = obj.stage
            
    from forms import ReqDetailsEditForm 
    view = EditView('requirementdetails', ok_url='/requirements/%s' % obj.requirement.id, 
        obj=obj, data=data, form_cls=ReqDetailsEditForm, post_created_form=post_created_form, 
        fields=fields, static_fields=static_fields, pre_save=pre_save)
        
    return view.run()
    
@expose('/requirements/details/<id>/delete')
def req_details_delete(id):
    from uliweb.utils.generic import DeleteView
    from uliweb.orm import get_model
    
    RequirementDetails = get_model('requirementdetails')
    obj = RequirementDetails.get(int(id))
    
    view = DeleteView('requirementdetails', ok_url='/requirements/%s' % obj.requirement.id, obj=obj)
    return view.run()

@expose('/requirements/query')
def requirements_query():
    from uliweb.orm import get_model
    Requirement = get_model('requirement')
    result = []
    query = Requirement.get_user_requirements(request.user, not_in=())
    for row in query:
        result.append([row.id, unicode(row)])
    return json(result)

@expose('/requirements/search')
def requirements_search():
    from uliweb.orm import get_model
    Requirement = get_model('requirement')
    
    txt = request.values.get('term')
    if not txt:
        return json([])
    
    result = Requirement.get_user_requirements(request.user).filter(Requirement.c.title.like('%' + txt + '%') | Requirement.c.req_id.like('%' + txt + '%')).values('id', 'title')
    return json([{'id':x[0], 'title':x[1]} for x in result])

@expose('/requirements/changes/<int:id>')
def requirements_changes(id):
    from uliweb.orm import get_model
    from uliweb.utils.generic import ListView
    
    Requirement = get_model('requirement')
    RequirementChange = get_model('requirementchange')
    condition = RequirementChange.c.requirement == int(id)
    
    req = Requirement.get(int(id))
    def action(value, obj):
        if req.can_modified(request.user):
            return '<a href="/requirements/changes/%s/edit/%d">编辑</a><a href="/requirements/changes/%s/delete/%d" onclick="return confirm(\'确定要删除当前记录吗？\');">删除</a>' % (id, obj.id, id, obj.id)
        else:
            return ''
    
    fields_convert_map = {'action':action}
    
    view = ListView('requirementchange', pagination=False, condition=condition,
        fields_convert_map=fields_convert_map)
    return view.run()['table']
    
@expose('/requirements/changes/<int:id>/add')
def requirements_changes_add(id):
    from uliweb.orm import get_model
    from uliweb.utils.generic import AddView

    view = AddView('requirementchange', '/requirements/%s#changes' % id,
        default_data={'requirement':int(id)})
    return view.run()

@expose('/requirements/changes/<int:id>/edit/<obj_id>')
def requirements_changes_edit(id, obj_id):
    from uliweb.orm import get_model
    from uliweb.utils.generic import EditView
    
    RequirementChange = get_model('requirementchange')
    obj = RequirementChange.get(int(obj_id))
    view = EditView('requirementchange', '/requirements/%s#changes' % id, obj=obj)
    return view.run()
  
@expose('/requirements/changes/<int:id>/delete/<obj_id>')
def requirements_changes_edit(id, obj_id):
    from uliweb.orm import get_model
    from uliweb.utils.generic import DeleteView
    
    RequirementChange = get_model('requirementchange')
    obj = RequirementChange.get(int(obj_id))
    view = DeleteView('requirementchange', '/requirements/%s#changes' % id, obj=obj)
    return view.run()

